package com.xjtu.se.homework.client.history.service.impl;

import com.xjtu.se.homework.client.FileProperties;
import com.xjtu.se.homework.client.history.bean.FinalResult;
import com.xjtu.se.homework.client.history.bean.HistoryResult;
import com.xjtu.se.homework.client.history.dao.HistoryDisplayDao;
import com.xjtu.se.homework.client.history.dto.HistoryDto;
import com.xjtu.se.homework.client.history.service.HistoryDisplayService;
import org.springframework.core.io.UrlResource;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.core.io.Resource;

import java.io.BufferedInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;

@Service
@Transactional
public class HistoryDisplayServiceImpl implements HistoryDisplayService {
    @javax.annotation.Resource
    private HistoryDisplayDao historyDisplayDao;

    private final Path fileStorageLocation; // 文件在本地存储的地址

    public HistoryDisplayServiceImpl(FileProperties fileProperties) throws Exception {
        this.fileStorageLocation = Paths.get(fileProperties.getUploadDir()).toAbsolutePath().normalize();
        try {
            Files.createDirectories(this.fileStorageLocation);
        } catch (Exception e) {
            throw new Exception("Could not create the directory where the uploaded files will be stored.", e);
        }
    }

    @Override
    public List<FinalResult> findAllHistory(HistoryDto dto) {
        List<HistoryResult> historyResults = historyDisplayDao.findAllHistory(dto);
        List<FinalResult> finalResults = new ArrayList<>();
        for (int i = 0; i < historyResults.size(); i++) {
            HistoryResult historyResult = historyResults.get(i);
            System.out.println(historyResult.getSearch_image());
            UrlResource resource = null;
            byte[] bytes = null;
            try {
                resource = loadFileAsResource(historyResult.getSearch_image());
                InputStream inputStream = resource.getInputStream();
                bytes = inputStream.readAllBytes();
            } catch (Exception e) {
                e.printStackTrace();
            }
            finalResults.add(new FinalResult(historyResult.getQues_class(), historyResult.getAns_num(), bytes, historyResult.getItems(), historyResult.getSearch_time(), historyResult.getIs_marked()));
        }
        return finalResults;
    }

    /**
     * 加载文件
     * @param fileName 文件名
     * @return 文件
     */
    public UrlResource loadFileAsResource(String fileName) throws Exception {
        try {
            Path filePath = this.fileStorageLocation.resolve(fileName).normalize();
            System.out.println(filePath.toString());
            UrlResource resource = new UrlResource(filePath.toUri());
            if(resource.exists()) {
                return resource;
            } else {
                throw new FileNotFoundException("File not found " + fileName);
            }
        } catch (MalformedURLException e) {
            throw new Exception("File not found " + fileName, e);
        }
    }

    @Override
    public void modify(HistoryDto dto) {
        historyDisplayDao.modify(dto);
    }
}
